import { reactive, ref, Ref, toRaw } from "vue";
import { LoginVo } from "@/types/login";
import { useLoginStore } from "@/store/login.store";
import { registerInf } from "@/api/user.api";
import { RegisterUser } from "@/types/user";
import { toast } from "@/hooks/useToast";
export const useLogin = (): {
  form: LoginVo;
  isLogin: Ref<boolean>;
  login: () => void;
  register: () => void;
  switchType: () => void;
} => {
  const { loginInf } = useLoginStore();
  const form = reactive(new LoginVo());
  const isLogin = ref(true);
  const login = (): void => {
    if (!form.userName) {
      toast("用户名不能为空!");
      return;
    }
    if (!form.password) {
      toast("密码不能为空!");
      return;
    }
    loginInf(toRaw(form));
  };
  const register = async () => {
    if (!form.userName) {
      toast("用户名不能为空!");
      return;
    }
    if (!form.password) {
      toast("密码不能为空!");
      return;
    }
    const registerUser = new RegisterUser();
    registerUser.userName = form.userName;
    registerUser.password = form.password;
    const res = await registerInf(registerUser);
    if (res.code === 200) {
      isLogin.value = true;
    }
  };
  const switchType = (): void => {
    isLogin.value = !isLogin.value;
  };
  return {
    form,
    isLogin,
    login,
    register,
    switchType,
  };
};
